<template>
  <div class="main">
    <!-- 主容器 - 只在有可见内容时显示 -->
    <div class="content-container" v-show="showContentContainer && contentVisible">

      <!-- 逐字显示模式 - 不可编辑 -->
      <template v-if="shouldTypewriter">
        <div v-for="(activity, activityIndex) in filteredActivities" :key="'activity' + activityIndex"
          class="activity-item">
          <!-- 活动名称 -->
          <div class="content-item" v-show="shouldShowItem('activity' + activityIndex + '-name')">
            <h2 class="activity-title">
              <span v-for="(char, charIndex) in (typewriterTexts['activity' + activityIndex + '-name'] || '')"
                :key="'activity' + activityIndex + '-name-' + charIndex" class="char"
                style="font-size: 20px;font-weight: 1000;">
                {{ char }}
              </span>
            </h2>
          </div>

          <!-- 教学目标 -->
          <div class="content-item" v-show="shouldShowItem('activity' + activityIndex + '-target')">
            <h3 class="content-title">教学目标</h3>
            <p class="content-text">
              <span v-for="(char, charIndex) in (typewriterTexts['activity' + activityIndex + '-target'] || '')"
                :key="'activity' + activityIndex + '-target-' + charIndex" class="char">
                {{ char }}
              </span>
            </p>
          </div>

          <!-- 活动步骤 -->
          <div class="content-item">
            <div v-for="(step, stepIndex) in activity.steps" :key="'activity' + activityIndex + '-step' + stepIndex"
              v-show="shouldShowItem('activity' + activityIndex + '-step' + stepIndex)">
              <p class="content-text">
                <span
                  v-for="(char, charIndex) in (typewriterTexts['activity' + activityIndex + '-step' + stepIndex] || '')"
                  :key="'activity' + activityIndex + '-step' + stepIndex + '-' + charIndex" :class="{
                    'char': true,
                    'bold-first-sentence': stepIndex === 0,
                    'other-sentence': stepIndex !== 0
                  }">
                  {{ char }}
                </span>
              </p>
            </div>
          </div>
        </div>
      </template>

      <!-- 直接显示模式 - 可编辑 -->
      <template v-else>
        <div v-for="(activity, activityIndex) in activities" :key="'activity' + activityIndex" class="activity-item">
          <!-- 编辑控制按钮 -->
          <div class="edit-controls">
            <button @click="removeActivity(activityIndex)" class="edit-btn delete-btn">删除活动</button>
            <button @click="addNewActivity(activityIndex)" class="edit-btn add-btn">添加活动</button>
          </div>
          
          <h2 class="activity-title" contenteditable="true" @blur="updateActivityName(activityIndex, $event)">
            {{ activity.name }}
          </h2>
          <div class="content-item">
            <h3 class="content-title">教学目标</h3>
            <p class="content-text" contenteditable="true" @blur="updateActivityTarget(activityIndex, $event)">
              {{ activity.target }}
            </p>
          </div>
          <div class="content-item">
            <div v-for="(step, stepIndex) in activity.steps" :key="'activity' + activityIndex + '-step' + stepIndex">
              <p class="content-text" :class="{ 'bold-first-sentence': stepIndex === 0 }"
                 contenteditable="true" 
                 @blur="updateActivityStep(activityIndex, stepIndex, $event)"
                 @keydown.enter.prevent="addNewStep(activityIndex, stepIndex, $event)">
                {{ step }}
              </p>
              <button v-if="stepIndex > 0" @click="removeStep(activityIndex, stepIndex)" 
                      class="step-delete-btn">删除步骤</button>
            </div>
            <button @click="addNewStep(activityIndex, activity.steps.length)" 
                    class="add-step-btn">+ 添加步骤</button>
          </div>
        </div>
      </template>
      
      <!-- 添加新活动的按钮 -->
      <div class="add-activity-container" v-if="!shouldTypewriter">
        <button @click="addNewActivity(activities.length)" class="add-activity-btn">+ 添加新活动</button>
      </div>
    </div>

    <!-- 等待状态 -->
    <Wait v-if="showWaitState" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue';
import { useCounterStore } from '@/stores/counter';
import axios from 'axios';
import Wait from '../Wait.vue';

const Store = useCounterStore();

// 响应式数据
const activities = ref<any[]>([]);
const typewriterTexts = ref<Record<string, string>>({});
const isLoading = ref(false);
const isDataLoaded = ref(false);
const shouldTypewriter = ref(true);

const emit = defineEmits<{
  (e: 'toNextStep', param: number): void;
}>();

// 计算属性
const filteredActivities = computed(() => {
  return activities.value.filter((_, index) => {
    return typewriterTexts.value[`activity${index}-name`]?.length > 0 ||
      !shouldTypewriter.value;
  });
});

const showContentContainer = computed(() => {
  return Store.AITeach?.Step2?.state === 1 && isDataLoaded.value;
});

const contentVisible = computed(() => {
  if (!shouldTypewriter.value) return true;
  return Object.keys(typewriterTexts.value).some(key =>
    typewriterTexts.value[key]?.length > 0
  );
});

const showWaitState = computed(() => {
  return Store.AITeach?.Step2?.state === 1 && !isDataLoaded.value;
});

// 方法
function shouldShowItem(key: string): boolean {
  return !shouldTypewriter.value || typewriterTexts.value[key]?.length > 0;
}

const totalChars = ref(0);
const typedChars = ref(0);

function typeText(text: string, key: string) {
  let currentText = '';
  typewriterTexts.value[key] = '';

  const interval = setInterval(() => {
    if (currentText.length < text.length) {
      currentText = text.substring(0, currentText.length + 1);
      typewriterTexts.value = {
        ...typewriterTexts.value,
        [key]: currentText
      };

      if (currentText.length === text.length) {
        typedChars.value += text.length;
        if (typedChars.value >= totalChars.value) {
          emit('toNextStep', 3);
        }
      }
    } else {
      clearInterval(interval);
    }
  }, 30);
}

function startTypewriterEffect() {
  totalChars.value = 0;
  typedChars.value = 0;

  activities.value.forEach((activity, activityIndex) => {
    totalChars.value += activity.name.length;
    totalChars.value += activity.target.length;
    activity.steps.forEach((step: string) => {
      totalChars.value += step.length;
    });
  });

  let delay = 0;

  activities.value.forEach((activity, activityIndex) => {
    setTimeout(() => {
      typeText(activity.name, `activity${activityIndex}-name`);
    }, delay);
    delay += activity.name.length * 30 + 1000;

    setTimeout(() => {
      typeText(activity.target, `activity${activityIndex}-target`);
    }, delay);
    delay += activity.target.length * 30 + 1000;

    activity.steps.forEach((step: string, stepIndex: number) => {
      setTimeout(() => {
        typeText(step, `activity${activityIndex}-step${stepIndex}`);
      }, delay);
      delay += step.length * 30 + 200;
    });
  });

  if (totalChars.value === 0) {
    emit('toNextStep', 3);
  }
}

// 编辑相关方法
function updateActivityName(index: number, event: Event) {
  const newName = (event.target as HTMLElement).innerText;
  activities.value[index].name = newName;
  updateStore();
}

function updateActivityTarget(index: number, event: Event) {
  const newTarget = (event.target as HTMLElement).innerText;
  activities.value[index].target = newTarget;
  updateStore();
}

function updateActivityStep(activityIndex: number, stepIndex: number, event: Event) {
  const newStep = (event.target as HTMLElement).innerText;
  activities.value[activityIndex].steps[stepIndex] = newStep;
  updateStore();
}

function addNewStep(activityIndex: number, stepIndex: number, event?: Event) {
  if (event) {
    event.preventDefault();
  }
  
  const newStep = event ? (event.target as HTMLElement).innerText : '新步骤内容';
  activities.value[activityIndex].steps.splice(stepIndex + 1, 0, newStep);
  
  if (event) {
    (event.target as HTMLElement).innerText = '';
  }
  
  updateStore();
  
  nextTick(() => {
    const steps = document.querySelectorAll(`.activity-item:nth-child(${activityIndex + 1}) .content-text`);
    if (steps.length > stepIndex + 1) {
      (steps[stepIndex + 1] as HTMLElement).focus();
    }
  });
}

function removeStep(activityIndex: number, stepIndex: number) {
  activities.value[activityIndex].steps.splice(stepIndex, 1);
  updateStore();
}

function addNewActivity(index: number) {
  const newActivity = {
    name: '新活动名称',
    target: '新教学目标',
    steps: ['新活动步骤']
  };
  activities.value.splice(index + 1, 0, newActivity);
  updateStore();
  
  nextTick(() => {
    const activityTitles = document.querySelectorAll('.activity-title');
    if (activityTitles.length > index + 1) {
      (activityTitles[index + 1] as HTMLElement).focus();
    }
  });
}

function removeActivity(index: number) {
  if (activities.value.length > 1) {
    activities.value.splice(index, 1);
    updateStore();
  } else {
    alert('至少需要保留一个活动');
  }
}

function updateStore() {
  Store.$patch({
    AITeach: {
      Step2: {
        content: [...activities.value]
      }
    }
  });
}

// 生命周期
onMounted(async () => {
  console.log('Step2 组件挂载');

  typewriterTexts.value = {};
  isDataLoaded.value = false;

  if (!Store.AITeach?.Step2?.content || Store.AITeach.Step2.content.length === 0) {
    isLoading.value = true;

    try {
      const response = await axios({
        url: "https://m1.apifoxmock.com/m1/5997017-0-default/teacher/design/interaction",
        method: "GET",
        params: {
          text: Store.$state.AIClassQuestion
        }
      });

      if (response.data.code === 200) {
        const interactions = Array.isArray(response.data.data.interactions)
          ? response.data.data.interactions
          : [];

        Store.$patch({
          AITeach: {
            Step2: {
              content: interactions,
              state: 1
            }
          }
        });

        activities.value = interactions;
        isDataLoaded.value = true;

        if (shouldTypewriter.value) {
          await nextTick();
          startTypewriterEffect();
        }
      }
    } catch (error) {
      console.error("获取数据失败:", error);
    } finally {
      isLoading.value = false;
    }
  } else {
    activities.value = Store.AITeach.Step2.content;
    isDataLoaded.value = true;
    shouldTypewriter.value = false;
  }
});
</script>

<style scoped>
.content-container {
  opacity: 0;
  height: 0;
  overflow: hidden;
  transition: opacity 0.3s ease, height 0.3s ease;
}

.content-container:not(.hidden) {
  opacity: 1;
  height: auto;
}

.activity-item {
  margin-bottom: 30px;
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  border-left: 4px solid #409EFF;
  position: relative;
}

.edit-controls {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 8px;
}

.edit-btn {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  border: none;
  transition: all 0.2s;
}

.delete-btn {
  background-color: #4db5ff;
  color: white;
  position: relative;
  left:-30px;
  top:10px;
}

.delete-btn:hover {
  background-color: #25a4ff;
}

.add-btn {
  background-color: #52c41a;
  color: white;
  position: relative;
  left:-30px;
  top:10px;
}

.add-btn:hover {
  background-color: #73d13d;
}

.activity-title {
  font-size: 17px;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 2px solid #e1e4e8;
  outline: none;
}

[contenteditable="true"] {
  outline: none;
  border-bottom: 1px dashed #ccc;
  padding: 2px 4px;
  min-height: 1em;
}

[contenteditable="true"]:focus {
  border-bottom: 1px solid #409EFF;
  background-color: #f0f7ff;
}

.content-item {
  margin-bottom: 15px;
  padding: 12px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border-left: 1px solid #b7dbff;
}

.content-title {
  font-size: 16px;
  font-weight: bold;
  color: #34495e;
  margin-bottom: 8px;
}

.content-text {
  font-size: 15px;
  color: #333;
  line-height: 1.6;
  white-space: pre-wrap;
  margin-bottom: 8px;
  min-height: 1em;
}

.char {
  opacity: 0;
  animation: fadeIn 0.1s forwards;
}

@keyframes fadeIn {
  to {
    opacity: 1;
  }
}

.bold-first-sentence {
  font-size: 16px;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 15px;
  padding-bottom: 10px;
}

.step-delete-btn {
  background-color: #c7e8ff;
  color: #4db5ff;
  border: 1px solid #9ed8ff;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 12px;
  cursor: pointer;
  margin-left: 8px;
  margin-bottom: 10px;
}

.step-delete-btn:hover {
  background-color: #9ed3ff;
}

.add-step-btn {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px dashed #91d5ff;
  border-radius: 4px;
  padding: 4px 12px;
  font-size: 13px;
  cursor: pointer;
  margin-top: 8px;
  display: inline-block;
}

.add-step-btn:hover {
  background-color: #bae7ff;
}

.add-activity-container {
  text-align: center;
  margin-top: 20px;
}

.add-activity-btn {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px dashed #b7eb8f;
  border-radius: 4px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
}

.add-activity-btn:hover {
  background-color: #d9f7be;
}
</style>